package com.chen.seckill.controller;

import com.chen.seckill.error.BusinessException;
import com.chen.seckill.error.EmBusinessError;
import com.chen.seckill.response.CommonReturnType;
import com.chen.seckill.service.OrderService;
import com.chen.seckill.service.bo.OrderBO;
import com.chen.seckill.service.bo.UserBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/order")
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
public class OrderController extends BaseController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    // 封装下单请求
    @PostMapping("/createOrder")
    @ResponseBody
    public CommonReturnType createOrder(@RequestParam("itemId")Integer itemId,
                                        @RequestParam("amount")Integer amount,
                                        @RequestParam(name = "promoId", required = false)Integer promoId) throws BusinessException {
        Boolean is_login =(Boolean)httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (is_login == null || !is_login) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        // 获取登录用户信息
        UserBO userBO = (UserBO)httpServletRequest.getSession().getAttribute("LOGIN_USER");

        OrderBO orderBO = orderService.createOrder(userBO.getId(), itemId, promoId, amount);

        return CommonReturnType.create(orderBO);
    }

}
